﻿using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Diagnostics.Tracing;
using Sustainalytics.ESGRatings.Computing.Service.Exceptions;
using Sustainalytics.ESGComputing.Service.Mappers;
using Sustainalytics.ESGRatings.BusinessLogic.Computing;
using Sustainalytics.ESGRatings.DataContract.Governance;
using Serilog;

namespace Sustainalytics.ESGRatings.Computing.Service.Controllers
{
    [RoutePrefix("api/v1/governancecompute")]

    public class GovernanceComputeController : ApiController
    {
        private readonly ComputationEngine _engine;

        public GovernanceComputeController(ComputationEngine engine)
        {
            _engine = engine;
        }

        [Route("")]
        public HttpResponseMessage Post(GovernanceRatingOptionDto options)
        {
            EventSource.SetCurrentThreadActivityId(Request.GetCorrelationId());
            if (options == null)
            {
                throw new InvalidInput("Invalid computation options");
            }

            Stopwatch watch = new Stopwatch();
            watch.Start();

            using (
                var result = _engine.ComputeGovernanceRatings(
                    options.SetId,
                    options.MatrixId,
                    options.IncludeAggregatedWeights,
                    options.IncludeWeights))
            {
                watch.Stop();
                Log.Information($"computation elapsed {watch.ElapsedMilliseconds} ");

                var dto = new GovernanceRatingsDto { SetId = result.SetId, };

                var utils = new GovernanceComputeMap(result);
                dto.IssuesCodes = utils.ToIndicatorsGroupsDto();
                dto.CompanyRating = utils.GetRatings().ToList();

                return Request.CreateResponse(HttpStatusCode.OK, dto);
            }
        }
    }
}